package plugins

import (
	"database/sql"
	"fmt"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/schema"
	"lib/mall/v1/configs"
	"net/url"
	"time"
)

var sqlDb *sql.DB
var conn *gorm.DB

func init() {
	//var cstZone = time.FixedZone("CST", 8*3600) // 东八
	//time.Local = cstZone
	//time.LoadLocation("Asia/Shanghai")
	config := configs.NewConfig()
	timezone := url.QueryEscape("'Asia/Shanghai'")
	t, value := time.Parse("2006-01-02 15:04:05", "2017-06-20 18:16:15")
	fmt.Println("timezone:::", timezone, t, value)

	// 参考 https://github.com/go-sql-driver/mysql#dsn-data-source-name 获取详情
	dsn := fmt.Sprintf(
		"%s:%s@tcp(%s:%s)/%s?charset=utf8mb4&parseTime=true&loc=Local",
		//"%s:%s@tcp(%s:%s)/%s?charset=utf8mb4&parseTime=true&loc=Local&time_zone=%s",
		config.Database.UserName,
		config.Database.Password,
		config.Database.Host,
		config.Database.Port,
		config.Database.Name,
		//timezone,
	)
	var connectErr error
	conn, connectErr = gorm.Open(mysql.New(mysql.Config{
		DSN:                       dsn, // DSN data source name
		DefaultStringSize:         255, // string 类型字段的默认长度
		DisableDatetimePrecision:  true,
		SkipInitializeWithVersion: false,
	}), &gorm.Config{
		SkipDefaultTransaction:   true, // 跳过默认事务
		DisableNestedTransaction: false,
		NamingStrategy: schema.NamingStrategy{
			SingularTable: true, // 使用单数表名
		},
	})
	if connectErr != nil {
		panic(connectErr)
	}
	sqlDb, _ = conn.DB()
	sqlDb.SetMaxIdleConns(10)
	sqlDb.SetMaxOpenConns(100)
	sqlDb.SetConnMaxLifetime(time.Hour)
}

func SqlDb() *sql.DB {
	return sqlDb
}

func Db() *gorm.DB {
	return conn
}
